import { nextTick } from "vue";

const dragMove = {
  beforeMount(el, binding) {
    const screenWidth = document.body.clientWidth;
    const screenHeight = document.documentElement.clientHeight;
    const DragButton = el.querySelector(binding.value.DragButton);
    DragButton.style.cssText += ";cursor:move;";
    const DragWindow = el.querySelector(binding.value.DragWindow);
    if (binding.value.custom) {
      nextTick(() => {
        const { offsetWidth, offsetHeight } = DragWindow;
        const [left, top] = [screenWidth - offsetWidth, screenHeight - offsetHeight];
        DragWindow.style.cssText += `;left:${left / 2}px;top:${top / 2}px;`;
      });
    }
    const sty = (function () {
      const { currentStyle } = window.document;
      if (currentStyle) {
        return (dom, attr) => dom.currentStyle[attr];
      } else {
        return (dom, attr) => getComputedStyle(dom, null)[attr];
      }
    })();
    DragButton.onmousedown = (e) => {
      const disX = e.clientX - DragButton.offsetLeft;
      const disY = e.clientY - DragButton.offsetTop;
      const dragDomWidth = DragWindow.offsetWidth;
      const dragDomHeight = DragWindow.offsetHeight;
      const minDragDomLeft = DragWindow.offsetLeft;
      const maxDragDomLeft = screenWidth - DragWindow.offsetLeft - dragDomWidth;
      const minDragDomTop = DragWindow.offsetTop;
      const maxDragDomTop = screenHeight - DragWindow.offsetTop - dragDomHeight;
      let styL = sty(DragWindow, "left");
      let styT = sty(DragWindow, "top");
      if (styL.includes("%")) {
        styL = +document.body.clientWidth * (+styL.replace(/%/g, "") / 100);
        styT = +document.body.clientHeight * (+styT.replace(/%/g, "") / 100);
      } else {
        styL = +styL.replace(/px/g, "");
        styT = +styT.replace(/px/g, "");
      }
      document.onmousemove = e => {
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        if (-left > minDragDomLeft) {
          left = -minDragDomLeft;
        } else if (left > maxDragDomLeft) {
          left = maxDragDomLeft;
        }
        if (-top > minDragDomTop) {
          top = -minDragDomTop;
        } else if (top > maxDragDomTop) {
          top = maxDragDomTop;
        }
        DragWindow.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`;
      };
      document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };
  }
};

const directivesList = { dragMove }

const directives = {
    install: function (app) {
      Object.keys(directivesList).forEach(key => {
        app.directive(key, directivesList[key]);
      });
    }
  };

  export default directives;
